package com.yaofeng.mybatis.modules.sys.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yaofeng.mybatis.annotation.Log;
import com.yaofeng.mybatis.common.ErrorCodeEnum;
import com.yaofeng.mybatis.common.ResponseInfo;
import com.yaofeng.mybatis.exception.BusinessException;
import com.yaofeng.mybatis.modules.sys.entity.Menu;
import com.yaofeng.mybatis.modules.sys.entity.RoleMenu;
import com.yaofeng.mybatis.modules.sys.service.IMenuService;
import com.yaofeng.mybatis.modules.sys.service.IRoleMenuService;
import com.yaofeng.mybatis.modules.sys.vo.SelectTreeVo;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 菜单权限表 前端控制器
 * </p>
 *
 * @author yaofeng
 * @since 2019-11-12
 */
@RestController
@RequestMapping("/sys/menu")
public class MenuController {

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IRoleMenuService  roleMenuService;

    @GetMapping("/list")
    @RequiresAuthentication
    @Log(value = "菜单列表")
    public ResponseInfo list(@RequestParam Map<String, Object> params) {
        List<SelectTreeVo>  list  =  menuService.findMenuList(params);
        return ResponseInfo.success(list);
    }

    @GetMapping("/tree/list")
    @RequiresAuthentication
    @Log(value = "菜单树形列表")
    public ResponseInfo treeList() {
        List<SelectTreeVo> treeVoList  = menuService.buildSelectTreeNode();
        return ResponseInfo.success(treeVoList);
    }


     /**
     * 保存菜单
     * @param menu
     * @return
     */
    @PostMapping("/save")
    @RequiresAuthentication
    @Log(value = "保存菜单")
    public  ResponseInfo save(@RequestBody Menu menu){
        menuService.save(menu);
        return ResponseInfo.success();
    }


    /**
     * 更新菜单
     * @param menu
     * @return
     */
    @PutMapping("/update")
    @RequiresAuthentication
    @Log(value = "更新菜单")
    public  ResponseInfo update(@RequestBody  Menu menu){
        menuService.updateById(menu);
        return ResponseInfo.success();
    }


    /**
     * 删除菜单
     * @param id
     * @return
     */
    @DeleteMapping ("/delete")
    @RequiresAuthentication
    @Log(value = "删除菜单")
    public  ResponseInfo delete(Long id){
        // 判断是否存在子菜单
        int childMenuCount   =  menuService.count(Wrappers.<Menu>lambdaQuery().eq(Menu::getParentId,id));
        if(childMenuCount>0){
            throw new BusinessException(ErrorCodeEnum.MENU_CHILD_EXIST);
        }
        // 判断菜单是否已经授权给角色
        int  roleMenuCount   =  roleMenuService.count(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getMenuId,id));
        if(roleMenuCount>0){
            throw new BusinessException(ErrorCodeEnum.MENU_ROLE_EXIST);
        }
        menuService.removeById(id);
        return ResponseInfo.success();
    }




}
